import { InfiniteScroll } from 'antd-mobile'
import { useRef, useState } from 'react'
import { sleep } from 'antd-mobile/es/utils/sleep'
import ArticleItem from '@/components/ArticleItem'
import styles from './index.module.scss'
import { getArticleListApi } from '@/api/home'
import { ArticlesItem } from '@/types/data'
import { useHistory } from 'react-router-dom'

type Props = {
  channelId: number
}

const ArticleList = ({ channelId }: Props) => {
  const history = useHistory()

  const [data, setData] = useState<ArticlesItem[]>([])
  const [hasMore, setHasMore] = useState(true)
  const timestamp = useRef(Date.now())
  async function loadMore() {
    const {
      data: { results, pre_timestamp },
    } = await getArticleListApi({
      channel_id: channelId,
      timestamp: timestamp.current,
    })
    setData((val) => [...val, ...results])
    if (pre_timestamp) {
      timestamp.current = pre_timestamp
    } else {
      setHasMore(false)
    }
  }

  return (
    <div className={styles.root}>
      {/* 文章列表中的每一项 */}
      {data.map((item, index) => (
        <div
          key={item.art_id}
          className="article-item"
          onClick={() => history.push(`/article/${item.art_id}`)}
        >
          <ArticleItem type={item.cover.type} item={item} />
        </div>
      ))}
      {/*
        loadMore 加载数据的函数
        hasMore 布尔值，true 表示还有更多数据；false 表示没有更多数据了
      */}
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  )
}

export default ArticleList
